package com.warehouse.dao.impl;

import com.warehouse.dao.OrderDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Cargo;
import com.warehouse.entity.Order;
import org.hibernate.Query;

import java.util.List;

public class OrderDaoImpl implements OrderDao {
    @Override
    public int add(Order order) {
        try {
            HibernateUtil.currentSession().save(order);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int update(Order order) {
        try {
            HibernateUtil.currentSession().update(order);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public int delete(int id) {
        try {
            //先获取id
            Order order = (Order) HibernateUtil.currentSession().get(Order.class,id);
            HibernateUtil.currentSession().delete(order);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @Override
    public List<Order> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from Order o order by o.id desc");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from Order").list().size();
    }

    @Override
    public Order byId(int id) {
        Order order = (Order) HibernateUtil.currentSession().get(Order.class,id);
        return order;
    }

    @Override
    public List<Order> byAdminNum(int startPage, int pageSize, Integer name) {
        String hql = "";
        if (name == 1){
            hql = "from Order o where o.outTime = ''";
        }else{
            hql = "from Order o where o.outTime != ''";
        }
        Query query = HibernateUtil.currentSession().createQuery(hql);
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int countByAdminNum(Integer name) {
        String hql = "";
        if (name == 1){
            hql = "from Order o where o.outTime = ''";
        }else{
            hql = "from Order o where o.outTime != ''";
        }
        return HibernateUtil.currentSession().createQuery(hql).list().size();
    }
}
